var flags = true;
// 基于准备好的dom，初始化echarts实例
var container = document.getElementById('deviceMap');


var PIC = {
    part_center: './img/part_center.png',
    part_flag: './img/part_flag.png',
    unpart_flag: './img/unpart_flag.png',
}

const width = container.scrollWidth;
const height = container.scrollHeight || 500;


// 缩略图
const minimap = new G6.Minimap();


const graph = new G6.TreeGraph({
    container: 'deviceMap',
    width: width,
    height: height,
    pixelRatio: 2,
    linkCenter: true,
    fitView: true,
    fitViewPadding: [100, 400, 50, 50],
    modes: {
        default: [
            {
                type: 'collapse-expand',
                onChange: function onChange(item, collapsed) {
                    const data = item.getModel();
                    data.collapsed = collapsed;
                    return true;
                },
            },
            'drag-canvas',
            'zoom-canvas',
        ],
    },
    defaultNode: {
        size: 16,
        anchorPoints: [[0, 0.5], [1, 0.5]],
        style: {
            fill: '#40a9ff',
            stroke: '#096dd9'
        }
    },
    defaultEdge: {
        type: 'cubic-horizontal',
        style: {
            stroke: '#A3B1BF'
        }
    },
    layout: {
        type: 'mindmap',
        direction: 'H',
        horizontalGap: 30, // 调整这个值以改变水平间距
        getHeight: function getHeight() {
            return 16;
        },
        getWidth: function getWidth() {
            return 16;
        },
        getVGap: function getVGap() {
            return 5;
        },
        getHGap: function getHGap() {
            return 70;
        }
    },
    plugins: [minimap]

});





graph.edge(function (node) {
    let newVar = nodeMap.get(node.target);
    // 1:绿色(交换机和防火墙都连通) 2:黄色(交换机和防火墙有一个处于连通) 3:红色(交换机和防火墙都不通) 4:无资产
    let color = 'green';
    if (newVar === 1) {
        color = 'green';
    } else if (newVar === 2) {
        color = 'yellow';
    } else if (newVar === 3) {
        color = 'red';
    } else if (newVar === 4) {
        color = 'gray';
    } else {
        color = 'green';
    }
    return {
        type: 'cubic-horizontal',
        style: {
            stroke: color,
        },
    };
});

var centerX = 0;
var globalNodeId = "";
graph.node(function (node) {
    // console.log(node)
    if (node.id === globalNodeId) {
        centerX = node.x;
    }
    let pic = PIC.part_flag;
    if (node.root) {
        pic = PIC.part_center;
    } else {
        if (node.status === 4) {
            pic = PIC.unpart_flag;
        }
    }
    // let position = node.children && node.children.length > 0 ? 'left' : node.x > centerX ? 'right' : 'left';
    let position = node.children && node.children.length > 0 ? node.x > centerX ? 'right' : 'left' :  'left';
    if (node.children&&node.children.length>0){
        // 有子节点
        if (node.x > centerX){
            position='right'
        }else {
            position='left'
        }
    }else {
        // 当前是叶子节点
        if (node.x > centerX){
            position='right'
        }else {
            position='left'
        }
    }
    if (node.id === globalNodeId) {
        position = "bottom";
    }
    let collapsed = false;
    if (node.depth > 1) {
        collapsed = true;
    }
    return {
        size: 26,
        label: node.name,
        img: pic,
        type: 'image',
        labelCfg: {
            offset: 5,
            position: position,
            style: {
                fill: '#84B1F3',

            }
        },
        collapsed: collapsed,

    };
});

// 点击节点时自动缩放适应整个布局


var nodeMap = new Map();

function extractStatusMap(node, statusMap) {
    // 添加当前节点的数据到Map
    statusMap.set(node.id, node.status);

    // 递归处理子节点
    if (node.children && node.children.length > 0) {
        for (const childNode of node.children) {
            extractStatusMap(childNode, statusMap);
        }
    }
}

function init() {
    //市值机关图
    cityWeb();
}

function cityWeb() {
    let code = localStorage.getItem("defCode");
    let data = datas(code);
    console.log(data)
    let number = countNodesWithStatus(data, 4);
    $(".orgNum").html(number);
    if (number >= 80) {
        // 设置第三节的状态为缩放
        data = setCollapsedTrue(data);
    }

    graph.data(data);
    graph.render();
    graph.fitView();
}


// 点击节点时重新适配页面的函数




function datas(params) {
    let res = {}
    // 渲染左侧的结构
    $.ajax({
        url: './dst.json',
        method: 'GET',
        dataType: 'json',
        async: false, // 设置为异步请求
        success: function (data) {
            if (data && data.list.length > 0) {
                res = data.list[0];
                nodeMap = new Map();
                extractStatusMap(res, nodeMap)
                globalNodeId = res['id']
            }
            $(".orgNum").html(data.total);
        }
    });
    return res;

}

function getTime() {

    let times = new Date();
    const weekDays = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    const today = new Date();
    // 获取星期几
    const dayOfWeek = weekDays[today.getDay()];
    let date = times.getDate(), year = times.getFullYear(), month = times.getMonth(), hours = times.getHours(),
        min = times.getMinutes(), sec = times.getSeconds();
    let hss = isTwo(hours) + ':' + isTwo(min) + ':' + isTwo(sec);
    $('.hss').text(hss);
    $('.year').text(year);
    $('.monthdate').text(isTwo(month + 1) + '-' + isTwo(date));
    $('.week').text(dayOfWeek);
}

function isTwo(param) {
    return String(param).length >= 2 ? param : '0' + param
}

$('.cityname').on('click', (e) => {
    $('.' + e.target.classList[1]).addClass('selectcity')
});

$('.jump').on('click', (e) => {
    $('.jump').css({background: '#0D1119', border: '1px solid #015B87'})
    $('.' + e.target.classList[1]).css({background: '#0060AA', border: '1px solid #0060AA'});
});

function setCollapsedTrue(treeData) {
    // 使用 jQuery 的深拷贝函数
    const newData = $.extend(true, {}, treeData);

    // 修改新数据
    for (const rootNode of newData.children) {
        rootNode.collapsed = true;
    }
    return newData;

}

function countNodesWithStatus(treeData, targetStatus) {
    let count = 0;
    if (treeData.status !== targetStatus) {
        count = count + 1;
    }

    function countNodesRecursive(node) {
        if (node.status !== targetStatus) {
            count++;
        }

        for (const childNode of node.children) {
            countNodesRecursive(childNode);
        }
    }

    for (const rootNode of treeData.children) {
        countNodesRecursive(rootNode);
    }

    return count;
}

$(function () {
    init();

})
